<template>
  <view>
    <u-popup
      v-model="showFlag"
      mode="bottom"
      :closeable="true"
      height="100%"
      :custom-style="{ background: '#eee' }"
      border-radius="12"
      :z-index="99998"
    >
      <view>
        <view>
          <u-tabs
            v-if="showFlag"
            :list="list"
            :is-scroll="false"
            v-model="current"
            @change="change"
          ></u-tabs>
        </view>
        <view class="u-m-t-10">
          <swiper class="swiper" :current="current" :disable-touch="true">
            <!-- :style="`height:${px2rpx(screenHeight) - 80 - 10 - 20}rpx`" -->
            <swiper-item @touchmove.stop="stopTouchMove">
              <view class="u-p-l-20 u-p-r-20">
                <u-search
                  placeholder="按用户名模糊搜索"
                  v-model="queryInfo"
                  :show-action="false"
                  @search="userData(true)"
                ></u-search>
              </view>
              <scroll-view
                class="scroll-view_Y content-page"
                :style="`box-sizing:border-box`"
                scroll-y="true"
              >
                <view style="padding: 30rpx">
                  <cellSelectGroup
                    v-model:value="checkedKeys"
                    type="multiple"
                    @click="selectChange"
                  >
                    <cellSelectItem
                      v-for="item in userList"
                      :key="item.key"
                      :value="item.key"
                      >{{ item.title }}</cellSelectItem
                    >
                  </cellSelectGroup>
                </view>
              </scroll-view>
              <!-- </view> -->
            </swiper-item>
            <swiper-item @touchmove.stop="stopTouchMove">
              <view class="u-p-l-20 u-p-r-20">
                <u-search
                  placeholder="按角色名称模糊搜索"
                  v-model="queryInfo"
                  :show-action="false"
                  @search="roleData(true)"
                ></u-search>
              </view>
              <scroll-view
                class="scroll-view_Y content-page"
                :style="`box-sizing:border-box`"
                scroll-y="true"
              >
                <view style="padding: 30rpx">
                  <cellSelectGroup
                    v-model:value="checkedKeys"
                    type="multiple"
                    @click="selectChange"
                  >
                    <template v-for="item in roleTreeData">
                      <view class="u-m-t-20 u-m-b-20">
                        <u-tag :text="item.title" type="primary"></u-tag>
                      </view>
                      <cellSelectItem
                        v-for="el in item.children"
                        :key="el.key"
                        :value="el.key"
                        >{{ el.title }}</cellSelectItem
                      >
                    </template>
                  </cellSelectGroup>
                </view>
              </scroll-view>
            </swiper-item>
          </swiper>
        </view>
        <view class="btn-box">
          <u-button shape="circle" type="primary" @click="submit"
            >确定</u-button
          >
        </view>
      </view>
    </u-popup>

    <u-modal
      v-model="showModal"
      title="提示"
      content="切换类型选型卡，之前的内容将被清空，请确认后再操作"
      :show-cancel-button="true"
      :z-index="99999"
      @confirm="confirmModal"
      @cancel="cancelModal"
      ref="uModal"
      :async-close="true"
    ></u-modal>
  </view>
</template>
<script lang="ts" setup>
import cellSelectGroup from '@/components/cellSelect/cellSelectGroup.vue';
import cellSelectItem from '@/components/cellSelect/cellSelectItem.vue';
import { useUserStoreWidthOut } from '@/stores/user';
import { getOrgUserList, getOrgRoleList } from '@/api/modules/user';
import { getOrgProjectUserList } from '@/api/modules/project';

const userStore: any = useUserStoreWidthOut();

const props = defineProps({
  choosedKeys: {
    type: Array,
    default: () => [],
  },
  isShow: {
    type: Boolean,
    default: false,
  },
  memberType: {
    type: [Number, String],
    default: 0,
  },
  userType: {
    type: String,
    default: 'org',
  },
  projectId: {
    type: String,
    default: '',
  },
  gainType: {
    type: String,
    default: '',
  },
  roleType: {
    type: String,
    default: 'all', // all 项目角色和组织角色  org 组织角色  project 项目角色
  },
  labels: {
    type: Array,
    default: () => [],
  },
});
const emits = defineEmits(['submit']);

const current = ref(0);
const showFlag = ref(false);
const queryInfo = ref('');
const list = [
  {
    name: '人员',
  },
  {
    name: '角色',
  },
];

const initData = (isSearch = false) => {
  if (props.gainType === 'user' || !props.gainType) {
    if (props.gainType === 'user') {
      current.value = 0;
    }
    userData(isSearch);
  }
  if (props.gainType === 'role' || !props.gainType) {
    if (props.gainType === 'role') {
      current.value = 1;
    }
    roleData(isSearch);
  }
};

const userList = ref<any[]>([]);
const checkedKeys = ref<any>([]);
const userData = (isSearch: boolean) => {
  const param: any = {
    appId: userStore.getAppId,
    orgId: userStore.getOrgInfo.orgId,
    pageNum: 1,
    pageSize: 500,
    availableFlag: 1, // 过滤掉停用用户
  };
  if (isSearch) {
    param.queryInfo = queryInfo.value;
  }
  let fn;
  if (props.userType === 'project') {
    param.projectId = props.projectId;
    fn = getOrgProjectUserList;
  } else {
    fn = getOrgUserList;
  }
  fn(param).then((res: any) => {
    const tempArr = res.list.filter((item: any) => {
      return item.accountProjectStatus !== 0;
    });
    if (tempArr.length) {
      userList.value = tempArr.map((item: any) => {
        return {
          title: item.name,
          key: item.userId,
        };
      });
    }
  });
};

const myRoleType = ref(props.roleType);
const roleTreeData = ref<any[]>([]);
const roleData = (isSearch: boolean) => {
  const param: any = {
    orgId: userStore.getOrgInfo.orgId,
    appId: '3050096807037108231',
  };
  if (isSearch) {
    param.queryInfo = queryInfo.value;
  }
  getOrgRoleList(param).then((res: any) => {
    roleTreeData.value = [];
    res.forEach((item: any) => {
      if (props.projectId && item.flag === 0) {
        return;
      }
      const tempArr: any = [];
      if (item.roleList && item.roleList.length > 0) {
        const roleMark = [
          '机构角色',
          '专业角色',
          '伦理委员会',
          'CRO',
          'SMO',
          '申办方',
          '其他',
        ];
        item.roleList.forEach((item: any) => {
          let title = item.roleName;
          if (item.roleMark) {
            title = title + ' (' + roleMark[item.roleMark * 1 - 1] + ')';
          }
          tempArr.push({
            title: title,
            key: item.roleId,
            isProject: item.isProject,
          });
        });
        // 如果只要项目角色，flag为0 是组织，所以return
        if (myRoleType.value === 'project' && item.flag === 0) {
          return;
        }
        // 如果只要组织角色，flag为1 是项目，所以return
        if (myRoleType.value === 'org' && item.flag === 1) {
          return;
        }
        roleTreeData.value.push({
          title: item.flag == 0 ? '组织角色' : '项目角色',
          key: item.flag,
          children: tempArr,
        });
      }
    });
  });
};

const stopTouchMove = () => {
  return true;
};

const submit = () => {
  emits('submit', {
    type: current.value,
    data: checkedKeys.value,
    labels: labels.value,
  });
  showFlag.value = false;
};

const labels = ref<any[]>([]);
const selectChange = (e: string) => {
  if (current.value === 0) {
    const currItem = userList.value.find((item) => item.key === e);
    const index = labels.value.findIndex((item) => item === currItem.title);
    if (index > -1) {
      if (labels.value.length === 1) return;
      labels.value.splice(index, 1);
    } else {
      labels.value.push(currItem.title);
    }
  } else {
    let currItem: any = null;
    roleTreeData.value.forEach((item) => {
      item.children.forEach((el: any) => {
        if (e === el.key) {
          currItem = el;
        }
      });
    });
    const index = labels.value.findIndex((item) => item === currItem?.title);
    if (index > -1) {
      if (labels.value.length === 1) return;
      labels.value.splice(index, 1);
    } else {
      labels.value.push(currItem.title);
    }
  }
};

const show = () => {
  showFlag.value = true;
  queryInfo.value = '';
  checkedKeys.value = props.choosedKeys;
  console.log(props);
  labels.value = props.labels || [];
  initData();
};

const showModal = ref(false);
const change = () => {
  queryInfo.value = '';
  labels.value = [];
  console.log(checkedKeys.value.length);
  if (checkedKeys.value.length === 0) {
    return;
  }
  showModal.value = true;
};

const confirmModal = () => {
  checkedKeys.value = [];
  showModal.value = false;
};
const cancelModal = () => {
  if (current.value === 1) {
    current.value = 0;
  } else {
    current.value = 1;
  }
};

defineExpose({
  show,
});
</script>
<style lang="scss">
.swiper {
  height: calc(100vh - 220rpx - env(safe-area-inset-bottom));
  .swiper-item {
    display: block;
    overflow-y: auto;
  }
}
.btn-box {
  position: absolute;
  bottom: env(safe-area-inset-bottom);
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
}
.content-page {
  height: calc(100vh - 284rpx - env(safe-area-inset-bottom));
}
</style>
